using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CPlayer : MonoBehaviour
{   
    //瓶子的基本属性
    [SerializeField]
    private int m_maxHealth = 100;//初始最大血量
    private int m_currentHealth;//瓶子的血量
    private float m_recoil = 10f;//后坐力
    private float m_angleRecoil = 50f;
    private float m_speedLimit = 100f;//速度
    private bool m_isDead = false;//是否死亡
    private float m_currentSpeedLimit;
    
    [SerializeField]
    private CBulletShoot m_bulletShooter;
    [SerializeField]
    private GameObject m_bulletPrefab;
    private const float m_speedOnNet = 2.5f;//在网内的速度
    private Rigidbody2D m_rigidbody;//刚体
    
    
    
   
    
    public void changeHealth(int damage)
    {
        if(m_isDead == true) return;
        
        m_currentHealth-=damage;
        if (m_currentHealth <= 0)
        {
            m_isDead = true;
            Die();
        }
        
    }

    public void Die()
    {
        
        UnityEngine.Object.Destroy(this.gameObject);
    }

    public void Attack()
    {
        
        Vector2 recoilDirection=-this.transform.right;
        m_rigidbody.AddForce(recoilDirection*m_recoil,ForceMode2D.Impulse);
        m_rigidbody.AddTorque(m_angleRecoil,ForceMode2D.Impulse);
        UnityEngine.Object.Instantiate<GameObject>(m_bulletPrefab,this.transform.position+0.2f*this.transform.right,
            Quaternion.Euler(this.transform.eulerAngles+new Vector3(0f,0f,180f)));
    }
    
    void Start()
    {
        m_rigidbody = GetComponent<Rigidbody2D>();
        m_currentSpeedLimit = m_speedLimit;
        
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("spiderNet"))
        {
            m_currentSpeedLimit=m_speedOnNet;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("spiderNet"))
        {
            m_currentSpeedLimit = m_speedLimit;
        }
    }
    
    
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            this.Attack();
        }
        
        if (this.m_rigidbody.velocity.magnitude > m_currentSpeedLimit)
        {
            this.m_rigidbody.velocity = m_rigidbody.velocity.normalized * m_currentSpeedLimit;
        }

        if (Mathf.Abs(this.m_rigidbody.angularVelocity) > 500f)
        {
            this.m_rigidbody.angularVelocity = Mathf.Sign(m_rigidbody.angularVelocity) * 500f;
        }
    }
}
